package database

import (
	"context"
	"database/sql"
	"fmt"
	"time"

	"changeme/internal/models"
)

// Middleware 中间件函数类型
type Middleware func(DatabaseDriver) DatabaseDriver

// MiddlewareChain 中间件链
type MiddlewareChain struct {
	middlewares []Middleware
}

// NewMiddlewareChain 创建中间件链
func NewMiddlewareChain(middlewares ...Middleware) *MiddlewareChain {
	return &MiddlewareChain{
		middlewares: middlewares,
	}
}

// Apply 应用中间件链到驱动
func (mc *MiddlewareChain) Apply(driver DatabaseDriver) DatabaseDriver {
	result := driver
	// 反向应用中间件，确保第一个中间件在最外层
	for i := len(mc.middlewares) - 1; i >= 0; i-- {
		result = mc.middlewares[i](result)
	}
	return result
}

// Logger 日志接口
type Logger interface {
	Debug(msg string, args ...interface{})
	Info(msg string, args ...interface{})
	Warn(msg string, args ...interface{})
	Error(msg string, args ...interface{})
}

// 以下是使用结构化Logger的LoggingMiddleware实现
type loggingMiddleware struct {
	driver DatabaseDriver
	logger Logger
}

// NewLoggingMiddleware 创建日志中间件
func NewLoggingMiddleware(logger Logger) Middleware {
	return func(driver DatabaseDriver) DatabaseDriver {
		return &loggingMiddleware{
			driver: driver,
			logger: logger,
		}
	}
}

// Connect 连接数据库
func (m *loggingMiddleware) Connect(config *models.DatabaseConfig) error {
	m.logger.Debug("Connecting to database", "type", config.Type, "host", config.Host, "port", config.Port)
	start := time.Now()
	err := m.driver.Connect(config)
	elapsed := time.Since(start)

	if err != nil {
		m.logger.Error("Failed to connect to database", "error", err, "elapsed", elapsed)
	} else {
		m.logger.Info("Connected to database", "elapsed", elapsed)
	}

	return err
}

// Disconnect 断开连接
func (m *loggingMiddleware) Disconnect() error {
	m.logger.Debug("Disconnecting from database")
	start := time.Now()
	err := m.driver.Disconnect()
	elapsed := time.Since(start)

	if err != nil {
		m.logger.Error("Failed to disconnect from database", "error", err, "elapsed", elapsed)
	} else {
		m.logger.Info("Disconnected from database", "elapsed", elapsed)
	}

	return err
}

// Ping 测试连接
func (m *loggingMiddleware) Ping() error {
	m.logger.Debug("Pinging database")
	start := time.Now()
	err := m.driver.Ping()
	elapsed := time.Since(start)

	if err != nil {
		m.logger.Error("Failed to ping database", "error", err, "elapsed", elapsed)
	} else {
		m.logger.Debug("Pinged database", "elapsed", elapsed)
	}

	return err
}

// IsConnected 是否已连接
func (m *loggingMiddleware) IsConnected() bool {
	return m.driver.IsConnected()
}

// GetVersion 获取版本
func (m *loggingMiddleware) GetVersion() (string, error) {
	m.logger.Debug("Getting database version")
	start := time.Now()
	version, err := m.driver.GetVersion()
	elapsed := time.Since(start)

	if err != nil {
		m.logger.Error("Failed to get database version", "error", err, "elapsed", elapsed)
	} else {
		m.logger.Debug("Got database version", "version", version, "elapsed", elapsed)
	}

	return version, err
}

// ListDatabases 列出数据库
func (m *loggingMiddleware) ListDatabases(ctx context.Context) ([]models.DatabaseInfo, error) {
	m.logger.Debug("Listing databases")
	start := time.Now()
	dbs, err := m.driver.ListDatabases(ctx)
	elapsed := time.Since(start)

	if err != nil {
		m.logger.Error("Failed to list databases", "error", err, "elapsed", elapsed)
	} else {
		m.logger.Debug("Listed databases", "count", len(dbs), "elapsed", elapsed)
	}

	return dbs, err
}

// ListTables 列出表
func (m *loggingMiddleware) ListTables(ctx context.Context, database string) ([]models.TableInfo, error) {
	m.logger.Debug("Listing tables", "database", database)
	start := time.Now()
	tables, err := m.driver.ListTables(ctx, database)
	elapsed := time.Since(start)

	if err != nil {
		m.logger.Error("Failed to list tables", "database", database, "error", err, "elapsed", elapsed)
	} else {
		m.logger.Debug("Listed tables", "database", database, "count", len(tables), "elapsed", elapsed)
	}

	return tables, err
}

// GetTableColumns 获取表列
func (m *loggingMiddleware) GetTableColumns(ctx context.Context, database, table string) ([]models.ColumnInfo, error) {
	m.logger.Debug("Getting table columns", "database", database, "table", table)
	start := time.Now()
	columns, err := m.driver.GetTableColumns(ctx, database, table)
	elapsed := time.Since(start)

	if err != nil {
		m.logger.Error("Failed to get table columns", "database", database, "table", table, "error", err, "elapsed", elapsed)
	} else {
		m.logger.Debug("Got table columns", "database", database, "table", table, "count", len(columns), "elapsed", elapsed)
	}

	return columns, err
}

// GetTableIndexes 获取表索引
func (m *loggingMiddleware) GetTableIndexes(ctx context.Context, database, table string) ([]models.IndexInfo, error) {
	m.logger.Debug("Getting table indexes", "database", database, "table", table)
	start := time.Now()
	indexes, err := m.driver.GetTableIndexes(ctx, database, table)
	elapsed := time.Since(start)

	if err != nil {
		m.logger.Error("Failed to get table indexes", "database", database, "table", table, "error", err, "elapsed", elapsed)
	} else {
		m.logger.Debug("Got table indexes", "database", database, "table", table, "count", len(indexes), "elapsed", elapsed)
	}

	return indexes, err
}

// ExecuteQuery 执行查询
func (m *loggingMiddleware) ExecuteQuery(ctx context.Context, query string, args ...interface{}) (*models.QueryResult, error) {
	m.logger.Debug("Executing query", "query", truncateQuery(query, 100), "args", args)
	start := time.Now()
	result, err := m.driver.ExecuteQuery(ctx, query, args...)
	elapsed := time.Since(start)

	if err != nil {
		m.logger.Error("Failed to execute query", "query", truncateQuery(query, 100), "error", err, "elapsed", elapsed)
	} else if result != nil && result.Error != "" {
		m.logger.Error("Query execution error", "query", truncateQuery(query, 100), "error", result.Error, "elapsed", elapsed)
	} else if result != nil {
		m.logger.Debug("Executed query", "query", truncateQuery(query, 100), "rowCount", result.RowCount, "elapsed", elapsed)
	}

	return result, err
}

// ExecuteNonQuery 执行非查询
func (m *loggingMiddleware) ExecuteNonQuery(ctx context.Context, query string, args ...interface{}) (int64, error) {
	m.logger.Debug("Executing non-query", "query", truncateQuery(query, 100), "args", args)
	start := time.Now()
	rowsAffected, err := m.driver.ExecuteNonQuery(ctx, query, args...)
	elapsed := time.Since(start)

	if err != nil {
		m.logger.Error("Failed to execute non-query", "query", truncateQuery(query, 100), "error", err, "elapsed", elapsed)
	} else {
		m.logger.Debug("Executed non-query", "query", truncateQuery(query, 100), "rowsAffected", rowsAffected, "elapsed", elapsed)
	}

	return rowsAffected, err
}

// BeginTransaction 开始事务
func (m *loggingMiddleware) BeginTransaction(ctx context.Context) (DatabaseTransaction, error) {
	m.logger.Debug("Beginning transaction")
	start := time.Now()
	tx, err := m.driver.BeginTransaction(ctx)
	elapsed := time.Since(start)

	if err != nil {
		m.logger.Error("Failed to begin transaction", "error", err, "elapsed", elapsed)
		return nil, err
	}

	m.logger.Debug("Began transaction", "elapsed", elapsed)
	return &loggingTransaction{
		tx:     tx,
		logger: m.logger,
	}, nil
}

// GetRawConnection 获取原始连接
func (m *loggingMiddleware) GetRawConnection() interface{} {
	return m.driver.GetRawConnection()
}

// GetCapabilities 获取数据库能力
func (m *loggingMiddleware) GetCapabilities() DatabaseCapabilities {
	return m.driver.GetCapabilities()
}

// GenerateCreateTableSQL 生成创建表SQL
func (m *loggingMiddleware) GenerateCreateTableSQL(database string, tableSchema *models.TableSchema) (string, error) {
	m.logger.Debug("Generating CREATE TABLE SQL", "database", database, "table", tableSchema.Name)
	start := time.Now()
	sql, err := m.driver.GenerateCreateTableSQL(database, tableSchema)
	elapsed := time.Since(start)

	if err != nil {
		m.logger.Error("Failed to generate CREATE TABLE SQL", "error", err, "elapsed", elapsed)
	} else {
		m.logger.Debug("Generated CREATE TABLE SQL", "elapsed", elapsed)
	}

	return sql, err
}

// GenerateAlterTableSQL 生成修改表SQL
func (m *loggingMiddleware) GenerateAlterTableSQL(database, table string, alterSchema *models.TableAlterSchema) ([]string, error) {
	m.logger.Debug("Generating ALTER TABLE SQL", "database", database, "table", table)
	start := time.Now()
	sqls, err := m.driver.GenerateAlterTableSQL(database, table, alterSchema)
	elapsed := time.Since(start)

	if err != nil {
		m.logger.Error("Failed to generate ALTER TABLE SQL", "error", err, "elapsed", elapsed)
	} else {
		m.logger.Debug("Generated ALTER TABLE SQL", "count", len(sqls), "elapsed", elapsed)
	}

	return sqls, err
}

// GenerateDropTableSQL 生成删除表SQL
func (m *loggingMiddleware) GenerateDropTableSQL(database, table string, cascade bool) string {
	m.logger.Debug("Generating DROP TABLE SQL", "database", database, "table", table, "cascade", cascade)
	return m.driver.GenerateDropTableSQL(database, table, cascade)
}

// GenerateRenameTableSQL 生成重命名表SQL
func (m *loggingMiddleware) GenerateRenameTableSQL(database, oldTable, newTable string) string {
	m.logger.Debug("Generating RENAME TABLE SQL", "database", database, "oldTable", oldTable, "newTable", newTable)
	return m.driver.GenerateRenameTableSQL(database, oldTable, newTable)
}

// GenerateTruncateTableSQL 生成清空表SQL
func (m *loggingMiddleware) GenerateTruncateTableSQL(database, table string) string {
	m.logger.Debug("Generating TRUNCATE TABLE SQL", "database", database, "table", table)
	return m.driver.GenerateTruncateTableSQL(database, table)
}

// GetTableDDL 获取表DDL
func (m *loggingMiddleware) GetTableDDL(database, table string) (string, error) {
	m.logger.Debug("Getting table DDL", "database", database, "table", table)
	start := time.Now()
	ddl, err := m.driver.GetTableDDL(database, table)
	elapsed := time.Since(start)

	if err != nil {
		m.logger.Error("Failed to get table DDL", "error", err, "elapsed", elapsed)
	} else {
		m.logger.Debug("Got table DDL", "elapsed", elapsed)
	}

	return ddl, err
}

// loggingTransaction 日志事务
type loggingTransaction struct {
	tx     DatabaseTransaction
	logger Logger
}

// Commit 提交事务
func (t *loggingTransaction) Commit() error {
	t.logger.Debug("Committing transaction")
	start := time.Now()
	err := t.tx.Commit()
	elapsed := time.Since(start)

	if err != nil {
		t.logger.Error("Failed to commit transaction", "error", err, "elapsed", elapsed)
	} else {
		t.logger.Debug("Committed transaction", "elapsed", elapsed)
	}

	return err
}

// Rollback 回滚事务
func (t *loggingTransaction) Rollback() error {
	t.logger.Debug("Rolling back transaction")
	start := time.Now()
	err := t.tx.Rollback()
	elapsed := time.Since(start)

	if err != nil {
		t.logger.Error("Failed to rollback transaction", "error", err, "elapsed", elapsed)
	} else {
		t.logger.Debug("Rolled back transaction", "elapsed", elapsed)
	}

	return err
}

// ExecuteQuery 在事务中执行查询
func (t *loggingTransaction) ExecuteQuery(ctx context.Context, query string, args ...interface{}) (*models.QueryResult, error) {
	t.logger.Debug("Executing query in transaction", "query", truncateQuery(query, 100), "args", args)
	start := time.Now()
	result, err := t.tx.ExecuteQuery(ctx, query, args...)
	elapsed := time.Since(start)

	if err != nil {
		t.logger.Error("Failed to execute query in transaction", "query", truncateQuery(query, 100), "error", err, "elapsed", elapsed)
	} else if result != nil && result.Error != "" {
		t.logger.Error("Query execution error in transaction", "query", truncateQuery(query, 100), "error", result.Error, "elapsed", elapsed)
	} else if result != nil {
		t.logger.Debug("Executed query in transaction", "query", truncateQuery(query, 100), "rowCount", result.RowCount, "elapsed", elapsed)
	}

	return result, err
}

// ExecuteNonQuery 在事务中执行非查询
func (t *loggingTransaction) ExecuteNonQuery(ctx context.Context, query string, args ...interface{}) (int64, error) {
	t.logger.Debug("Executing non-query in transaction", "query", truncateQuery(query, 100), "args", args)
	start := time.Now()
	rowsAffected, err := t.tx.ExecuteNonQuery(ctx, query, args...)
	elapsed := time.Since(start)

	if err != nil {
		t.logger.Error("Failed to execute non-query in transaction", "query", truncateQuery(query, 100), "error", err, "elapsed", elapsed)
	} else {
		t.logger.Debug("Executed non-query in transaction", "query", truncateQuery(query, 100), "rowsAffected", rowsAffected, "elapsed", elapsed)
	}

	return rowsAffected, err
}

// Exec 执行SQL
func (t *loggingTransaction) Exec(query string, args ...interface{}) (sql.Result, error) {
	t.logger.Debug("Executing SQL in transaction", "query", truncateQuery(query, 100), "args", args)
	start := time.Now()
	result, err := t.tx.Exec(query, args...)
	elapsed := time.Since(start)

	if err != nil {
		t.logger.Error("Failed to execute SQL in transaction", "query", truncateQuery(query, 100), "error", err, "elapsed", elapsed)
	} else {
		t.logger.Debug("Executed SQL in transaction", "query", truncateQuery(query, 100), "elapsed", elapsed)
	}

	return result, err
}

// MetricsCollector 指标收集器接口
type MetricsCollector interface {
	RecordOperation(operation string, duration time.Duration, err error)
	RecordQuery(query string, duration time.Duration, rows int, err error)
}

// MetricsMiddleware 指标收集中间件
type metricsMiddleware struct {
	driver    DatabaseDriver
	collector MetricsCollector
}

// NewMetricsMiddleware 创建指标中间件
func NewMetricsMiddleware(collector MetricsCollector) Middleware {
	return func(driver DatabaseDriver) DatabaseDriver {
		return &metricsMiddleware{
			driver:    driver,
			collector: collector,
		}
	}
}

func (md *metricsMiddleware) Connect(config *models.DatabaseConfig) error {
	start := time.Now()
	err := md.driver.Connect(config)
	md.collector.RecordOperation("connect", time.Since(start), err)
	return err
}

func (md *metricsMiddleware) Disconnect() error {
	start := time.Now()
	err := md.driver.Disconnect()
	md.collector.RecordOperation("disconnect", time.Since(start), err)
	return err
}

func (md *metricsMiddleware) Ping() error {
	return md.driver.Ping()
}

func (md *metricsMiddleware) IsConnected() bool {
	return md.driver.IsConnected()
}

func (md *metricsMiddleware) GetVersion() (string, error) {
	return md.driver.GetVersion()
}

func (md *metricsMiddleware) GetRawConnection() interface{} {
	return md.driver.GetRawConnection()
}

func (md *metricsMiddleware) GetCapabilities() DatabaseCapabilities {
	return md.driver.GetCapabilities()
}

func (md *metricsMiddleware) ListDatabases(ctx context.Context) ([]models.DatabaseInfo, error) {
	start := time.Now()
	result, err := md.driver.ListDatabases(ctx)
	md.collector.RecordOperation("list_databases", time.Since(start), err)
	return result, err
}

func (md *metricsMiddleware) ListTables(ctx context.Context, database string) ([]models.TableInfo, error) {
	start := time.Now()
	result, err := md.driver.ListTables(ctx, database)
	md.collector.RecordOperation("list_tables", time.Since(start), err)
	return result, err
}

func (md *metricsMiddleware) GetTableColumns(ctx context.Context, database, table string) ([]models.ColumnInfo, error) {
	start := time.Now()
	result, err := md.driver.GetTableColumns(ctx, database, table)
	md.collector.RecordOperation("get_table_columns", time.Since(start), err)
	return result, err
}

func (md *metricsMiddleware) GetTableIndexes(ctx context.Context, database, table string) ([]models.IndexInfo, error) {
	start := time.Now()
	result, err := md.driver.GetTableIndexes(ctx, database, table)
	md.collector.RecordOperation("get_table_indexes", time.Since(start), err)
	return result, err
}

func (md *metricsMiddleware) ExecuteQuery(ctx context.Context, query string, args ...interface{}) (*models.QueryResult, error) {
	start := time.Now()
	result, err := md.driver.ExecuteQuery(ctx, query, args...)

	rows := 0
	if result != nil {
		rows = result.RowCount
	}

	md.collector.RecordQuery(query, time.Since(start), rows, err)
	return result, err
}

func (md *metricsMiddleware) ExecuteNonQuery(ctx context.Context, query string, args ...interface{}) (int64, error) {
	start := time.Now()
	result, err := md.driver.ExecuteNonQuery(ctx, query, args...)
	md.collector.RecordOperation("execute_non_query", time.Since(start), err)
	return result, err
}

func (md *metricsMiddleware) BeginTransaction(ctx context.Context) (DatabaseTransaction, error) {
	start := time.Now()
	tx, err := md.driver.BeginTransaction(ctx)
	md.collector.RecordOperation("begin_transaction", time.Since(start), err)

	if err != nil {
		return nil, err
	}

	return tx, nil
}

// GenerateCreateTableSQL 生成创建表SQL
func (md *metricsMiddleware) GenerateCreateTableSQL(database string, tableSchema *models.TableSchema) (string, error) {
	start := time.Now()
	sql, err := md.driver.GenerateCreateTableSQL(database, tableSchema)
	md.collector.RecordOperation("generate_create_table_sql", time.Since(start), err)
	return sql, err
}

// GenerateAlterTableSQL 生成修改表SQL
func (md *metricsMiddleware) GenerateAlterTableSQL(database, table string, alterSchema *models.TableAlterSchema) ([]string, error) {
	start := time.Now()
	sqls, err := md.driver.GenerateAlterTableSQL(database, table, alterSchema)
	md.collector.RecordOperation("generate_alter_table_sql", time.Since(start), err)
	return sqls, err
}

// GenerateDropTableSQL 生成删除表SQL
func (md *metricsMiddleware) GenerateDropTableSQL(database, table string, cascade bool) string {
	return md.driver.GenerateDropTableSQL(database, table, cascade)
}

// GenerateRenameTableSQL 生成重命名表SQL
func (md *metricsMiddleware) GenerateRenameTableSQL(database, oldTable, newTable string) string {
	return md.driver.GenerateRenameTableSQL(database, oldTable, newTable)
}

// GenerateTruncateTableSQL 生成清空表SQL
func (md *metricsMiddleware) GenerateTruncateTableSQL(database, table string) string {
	return md.driver.GenerateTruncateTableSQL(database, table)
}

// GetTableDDL 获取表DDL
func (md *metricsMiddleware) GetTableDDL(database, table string) (string, error) {
	start := time.Now()
	ddl, err := md.driver.GetTableDDL(database, table)
	md.collector.RecordOperation("get_table_ddl", time.Since(start), err)
	return ddl, err
}

// RetryMiddleware 重试中间件
type retryMiddleware struct {
	driver     DatabaseDriver
	maxRetries int
	retryDelay time.Duration
}

// NewRetryMiddleware 创建重试中间件
func NewRetryMiddleware(maxRetries int, retryDelay time.Duration) Middleware {
	return func(driver DatabaseDriver) DatabaseDriver {
		return &retryMiddleware{
			driver:     driver,
			maxRetries: maxRetries,
			retryDelay: retryDelay,
		}
	}
}

// Connect 实现数据库连接方法
func (rd *retryMiddleware) Connect(config *models.DatabaseConfig) error {
	return rd.driver.Connect(config)
}

// Disconnect 实现数据库断开方法
func (rd *retryMiddleware) Disconnect() error {
	return rd.driver.Disconnect()
}

// Ping 实现数据库Ping方法
func (rd *retryMiddleware) Ping() error {
	return rd.driver.Ping()
}

// IsConnected 实现数据库连接状态检查方法
func (rd *retryMiddleware) IsConnected() bool {
	return rd.driver.IsConnected()
}

// GetVersion 实现获取数据库版本方法
func (rd *retryMiddleware) GetVersion() (string, error) {
	return rd.driver.GetVersion()
}

// GetRawConnection 实现获取原始连接方法
func (rd *retryMiddleware) GetRawConnection() interface{} {
	return rd.driver.GetRawConnection()
}

// GetCapabilities 实现获取数据库能力方法
func (rd *retryMiddleware) GetCapabilities() DatabaseCapabilities {
	return rd.driver.GetCapabilities()
}

// ListDatabases 实现列出数据库方法
func (rd *retryMiddleware) ListDatabases(ctx context.Context) ([]models.DatabaseInfo, error) {
	return rd.driver.ListDatabases(ctx)
}

// ListTables 实现列出表方法
func (rd *retryMiddleware) ListTables(ctx context.Context, database string) ([]models.TableInfo, error) {
	return rd.driver.ListTables(ctx, database)
}

// GetTableColumns 实现获取表列方法
func (rd *retryMiddleware) GetTableColumns(ctx context.Context, database, table string) ([]models.ColumnInfo, error) {
	return rd.driver.GetTableColumns(ctx, database, table)
}

// GetTableIndexes 实现获取表索引方法
func (rd *retryMiddleware) GetTableIndexes(ctx context.Context, database, table string) ([]models.IndexInfo, error) {
	return rd.driver.GetTableIndexes(ctx, database, table)
}

// ExecuteQuery 实现执行查询方法（带重试）
func (rd *retryMiddleware) ExecuteQuery(ctx context.Context, query string, args ...interface{}) (*models.QueryResult, error) {
	var lastErr error
	for i := 0; i <= rd.maxRetries; i++ {
		if i > 0 {
			select {
			case <-ctx.Done():
				return nil, ctx.Err()
			case <-time.After(rd.retryDelay * time.Duration(i)):
				// 指数退避
			}
		}

		result, err := rd.driver.ExecuteQuery(ctx, query, args...)
		if err == nil {
			return result, nil
		}

		// 检查是否可重试的错误
		if dbErr, ok := err.(*DatabaseError); ok && !dbErr.IsRetryable() {
			return result, err
		}

		lastErr = err
	}

	return nil, fmt.Errorf("query failed after %d retries: %w", rd.maxRetries, lastErr)
}

// ExecuteNonQuery 实现执行非查询方法（带重试）
func (rd *retryMiddleware) ExecuteNonQuery(ctx context.Context, query string, args ...interface{}) (int64, error) {
	var lastErr error
	var result int64

	for i := 0; i <= rd.maxRetries; i++ {
		if i > 0 {
			select {
			case <-ctx.Done():
				return 0, ctx.Err()
			case <-time.After(rd.retryDelay * time.Duration(i)):
				// 指数退避
			}
		}

		affected, err := rd.driver.ExecuteNonQuery(ctx, query, args...)
		if err == nil {
			return affected, nil
		}

		// 检查是否可重试的错误
		if dbErr, ok := err.(*DatabaseError); ok && !dbErr.IsRetryable() {
			return affected, err
		}

		result = affected
		lastErr = err
	}

	return result, fmt.Errorf("non-query failed after %d retries: %w", rd.maxRetries, lastErr)
}

// BeginTransaction 实现开始事务方法
func (rd *retryMiddleware) BeginTransaction(ctx context.Context) (DatabaseTransaction, error) {
	return rd.driver.BeginTransaction(ctx)
}

// GenerateCreateTableSQL 生成创建表SQL
func (rd *retryMiddleware) GenerateCreateTableSQL(database string, tableSchema *models.TableSchema) (string, error) {
	return rd.driver.GenerateCreateTableSQL(database, tableSchema)
}

// GenerateAlterTableSQL 生成修改表SQL
func (rd *retryMiddleware) GenerateAlterTableSQL(database, table string, alterSchema *models.TableAlterSchema) ([]string, error) {
	return rd.driver.GenerateAlterTableSQL(database, table, alterSchema)
}

// GenerateDropTableSQL 生成删除表SQL
func (rd *retryMiddleware) GenerateDropTableSQL(database, table string, cascade bool) string {
	return rd.driver.GenerateDropTableSQL(database, table, cascade)
}

// GenerateRenameTableSQL 生成重命名表SQL
func (rd *retryMiddleware) GenerateRenameTableSQL(database, oldTable, newTable string) string {
	return rd.driver.GenerateRenameTableSQL(database, oldTable, newTable)
}

// GenerateTruncateTableSQL 生成清空表SQL
func (rd *retryMiddleware) GenerateTruncateTableSQL(database, table string) string {
	return rd.driver.GenerateTruncateTableSQL(database, table)
}

// GetTableDDL 获取表DDL
func (rd *retryMiddleware) GetTableDDL(database, table string) (string, error) {
	return rd.driver.GetTableDDL(database, table)
}

// truncateQuery 截断查询字符串
func truncateQuery(query string, maxLen int) string {
	if len(query) <= maxLen {
		return query
	}
	return query[:maxLen] + "..."
}
